package org.fjsei.yewu.job.controller;

import md.specialEqp.Eqp;
import org.fjsei.yewu.dto.SearchResponse;
import org.fjsei.yewu.job.controller.model.CreateJobDetailsRequestModel;
import org.fjsei.yewu.job.controller.model.JobDetailModel;
import org.fjsei.yewu.job.controller.model.TestJobRequest;
import org.fjsei.yewu.job.service.QuartzJobManager;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.fjsei.yewu.job.service.SplitTask;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/*不同点：@RequiredArgsConstructor与Spring的依赖注入机制相结合，允许你通过构造函数注入依赖，而无需显式使用@Autowired注解。
* */
@RestController
@RequestMapping("/api/jobs")
@RequiredArgsConstructor
@Slf4j
@Validated
public class QuartzController {

    private final QuartzJobManager quartzJobManager;
    private final SplitTask splitTask;
/*Create or Update Job  没区分的 容易冲突 # POST::
{ "jobName": "infsyn-22", "groupName": "device",
  "mapData": { "abc": 123, "jjj": "wsx12s" } }
* */
    @PostMapping("new")
    public ResponseEntity<String> createOrUpdateJob(@RequestBody @Valid CreateJobDetailsRequestModel createJobDetailsRequestModel) {
        try {
            quartzJobManager.createOrUpdateJob(createJobDetailsRequestModel);

            return ResponseEntity.ok().body("Job created/updated successfully");
        } catch (Exception exception) {
            log.error("Failed to create/update jobs. {}", exception.getMessage(), exception);
            return ResponseEntity.internalServerError().body("Failed to create/update jobs." + exception.getMessage());
        }
    }

    // Read Job  /。 / groupName 必须非汉字的的，# url失败
    @GetMapping("/{jobName}/{groupName}")
    public JobDetailModel getJobDetails(@PathVariable String jobName, @PathVariable String groupName) {
        try {
            JobDetail jobDetails = quartzJobManager.getJobDetails(jobName, groupName);
            return Optional.ofNullable(jobDetails)
                    .map(jobDetail -> JobDetailModel.builder().jobName(jobDetail.getKey().getName()).groupName(jobDetail.getKey().getGroup()).build()).orElseThrow(() -> new RuntimeException("No jobs found with jobName " + jobName));
        } catch (Exception exception) {
            log.error("Failed to get jobs with jobName {}. Error is {}", jobName, exception.getMessage(), exception);
            throw new RuntimeException("Failed to get jobs with jobName " + jobName);
        }
    }

    //直接删除：但是已经触发执行的是无法停止的！还必须全部节点都重启！     Delete Job
//    @DeleteMapping("/{jobName}/{groupName}")
    @PostMapping(value = "delete")
    public String deleteJob(@RequestBody @Valid CreateJobDetailsRequestModel createJobDetailsRequestModel) {
        try {
            boolean isDeleted = this.quartzJobManager.deleteJob(createJobDetailsRequestModel);
            return isDeleted ? "Job deleted successfully: "  : "Job not found:";
        } catch (Exception exception) {
            log.error("Failed to delete jobs with Error is {}",  exception.getMessage(), exception);
            return "Failed to delete jobs: " + exception.getMessage();
        }
    }
    //立刻中断所有通道的运行！  不是本节点的也无法中断掉！
    @PostMapping(value = "pause")
    public String pauseJobAll(@RequestBody @Valid CreateJobDetailsRequestModel createJobDetailsRequestModel) {
        try {
            this.quartzJobManager.pauseJobAll(createJobDetailsRequestModel);
            return "Job paused successfully: " ;
        } catch (Exception exception) {
            log.error("Failed to pause jobs with . Error is {}", exception.getMessage(), exception);
            return "Failed to pause jobs: " + exception.getMessage();
        }
    }

    // Pause Job 汉字不行 groupName
    @PostMapping(value = "/{jobName}/{groupName}/pause")
    public String pauseJobOne(@PathVariable String jobName, @PathVariable String groupName) {
        try {
            this.quartzJobManager.pauseJob(jobName, groupName);
            return "Job paused successfully: " + jobName;
        } catch (Exception exception) {
            log.error("Failed to pause jobs with jobName {}. Error is {}", jobName, exception.getMessage(), exception);
            return "Failed to pause jobs: " + exception.getMessage();
        }
    }
    //不能上     @PostMapping(value = "/{jobName}/{groupName}/run")
    // Resume Job
    @PostMapping(value = "/{jobName}/{groupName}/run")
    public String resumeJob(@PathVariable String jobName, @PathVariable String groupName) {
        try {
            this.quartzJobManager.resumeJob(jobName, groupName);
            return "Job resumed successfully: " + jobName;
        } catch (Exception exception) {
            log.error("Failed to resume jobs with jobName {}. Error is {}", jobName, exception.getMessage(), exception);
            return "Failed to resume jobs: " + exception.getMessage();
        }
    }

    //Read All Jobs
    @GetMapping
    public Set<JobDetailModel> getAllJobDetails() throws SchedulerException {
        return this.quartzJobManager.getAllJobDetails().stream()
                .map(jobDetail -> JobDetailModel.builder().jobName(jobDetail.getKey().getName()).groupName(jobDetail.getKey().getGroup()).build())
                .collect(Collectors.toSet());
    }
    //public String initJob(@PathVariable String jobName, @PathVariable String groupName) {}
    @PostMapping("init")
    public String initJob(@RequestBody @Valid TestJobRequest req) {
        SearchResponse<? extends Eqp> some=splitTask.trySplit(req);
        try {

            return "Job 拆分总数: " + some.getPage().getTotalElements();
        } catch (Exception exception) {
            log.error("Failed to resume jobs with jobName {}. Error is {}", req.keyword, exception.getMessage(), exception);
            return "Failed to resume jobs: " + exception.getMessage();
        }
    }

    //已经运行无法停止的，重启的还需要手动恢复； Pause Job 汉字不行 groupName
    @PostMapping(value = "pauseAll")
    public String pauseAll() {
        try {
            this.quartzJobManager.pauseAll();
            return "Job pauseAll successfully: ";
        } catch (Exception exception) {
            log.error("Failed to pauseAll jobs . Error is {}",  exception.getMessage(), exception);
            return "Failed to pause jobs: " + exception.getMessage();
        }
    }
    @PostMapping(value = "resumeAll")
    public String resumeAll() {
        try {
            this.quartzJobManager.resumeAll();
            return "Job resumeAll successfully: ";
        } catch (Exception exception) {
            log.error("Failed to resumeAll jobs . Error is {}",  exception.getMessage(), exception);
            return "Failed to pause jobs: " + exception.getMessage();
        }
    }
    @PostMapping(value = "shutdown")
    public String shutdown() {
        try {
            this.quartzJobManager.shutdown();       //本节点机已经在运行的中断！集群的其它节点可没影响到！
            return "Job shutdown successfully: ";
        } catch (Exception exception) {
            log.error("Failed to shutdown jobs . Error is {}",  exception.getMessage(), exception);
            return "Failed to pause jobs: " + exception.getMessage();
        }
    }
    @PostMapping(value = "schedulerStart")
    public String schedulerStart() {
        try {
            this.quartzJobManager.start();
            return "Scheduler shutdown successfully: ";
        } catch (Exception exception) {
            log.error("Failed to shutdown Scheduler . Error is {}",  exception.getMessage(), exception);
            return "Failed to pause jobs: " + exception.getMessage();
        }
    }
    @PostMapping(value = "clear")
    public String clear() {
        try {
            this.quartzJobManager.clear();
            return "Scheduler clear successfully: ";
        } catch (Exception exception) {
            log.error("Failed to clear Scheduler . Error is {}",  exception.getMessage(), exception);
            return "Failed to pause jobs: " + exception.getMessage();
        }
    }
}
